<?php

namespace app\logic;

use app\models\Group;
use app\forms\GroupForm;
use app\models\Position;
use app\models\Department;
use app\models\UserProfile;
use yii\web\HttpException;
use yii\db\StaleObjectException;
use app\components\helpers\TreeHelper;
use app\components\helpers\DropListHelper;

/**
 * 组织逻辑类
 */
class GroupLogic extends BaseLogic
{
    /**
     * 组织首页
     * 展示 组织树、包含其它部门树、岗位树
     * @return array
     */
    public static function index()
    {
        $userProfile = UserProfile::getInfo(user()->id);
        $groupId = $userProfile['group_id'];
        $positionArr = Position::getListWithUserCount($groupId);
        $pidArr = array_column($positionArr, 'parentId');
        sort($pidArr);
        $position = TreeHelper::format($positionArr, $pidArr[0]);
        $deptType = Department::getTypeMapping();
        return ['group' => self::_getTree($groupId), 'position' => $position, 'deptType' => $deptType];
    }

    /**
     * 创建组织（ 接收表单数据 ）
     * @param $param
     * @throws HttpException
     */
    public static function create($param)
    {
        $form = self::_validateForm($param, 'create');
        $attr = $form->getAttributes();
        $attr['parent_id'] = $attr['parentId'];
        Group::newCreate($attr);
        throw new HttpException(200, 'OK');
    }

    /**
     * 编辑组织（ 接收表单数据 ）
     * @param $param
     * @throws HttpException
     */
    public static function update($param)
    {
        $form = self::_validateForm($param, 'update');
        $attr = $form->getAttributes();
        unset($attr['parentId'], $attr['id']);
        Group::updateByPk($attr, $form['id']);
        throw new HttpException(200, 'OK');
    }

    /**
     * 删除组织
     * @param $param
     * @throws \Throwable
     * @throws StaleObjectException
     */
    public static function delete($param)
    {
        $form = self::_validateForm($param, 'delete');
        $model = Group::findOne($form['id']);
        $childrenCount = $model->getChildrenCount();
        $deptCount = $model->getDeptCount();
        if ($deptCount || $childrenCount) {
            throw new HttpException(423);
        }
        $model->delete();
        throw new HttpException(200, 'OK');
    }

    /**
     * 组织下拉列表数据
     * @return array
     */
    public static function getDropList()
    {
        return self::_getList();
    }

    /**
     * 获取组织、部门 树结构
     * @return array[]
     */
    public static function getTreeList()
    {
        $userProfile = UserProfile::getInfo(user()->id);
        $groupId = $userProfile['group_id'];
        return ['group' => self::_getTree($groupId)];
    }

    /**
     * 获取组织编辑的信息
     * @param $param
     * @return array
     * @throws HttpException
     */
    public static function getInfo($param)
    {
        $form = self::_validateForm($param, 'get-info');
        $group = Group::getSingleByPk($form['id'], ['id', 'name', 'parent_id AS parentId', 'sort']);
        return ['group' => $group, 'list' => self::_getList()];
    }

    public static function getTreeForItemData()
    {
        return self::_getTreeForItemData([]);
    }

    /**
     * 参数、表单数据 验证
     * @param $param
     * @param $scenario
     * @return GroupForm
     * @throws HttpException
     */
    public static function _validateForm($param, $scenario)
    {
        $form = new GroupForm();
        $form->setScenario($scenario);
        $form->setAttributes($param);
        if (!$form->validate()) {
            throw new HttpException(400, $form->getFirstError());
        }
        return $form;
    }

    /**
     * Notes:获取自定义授权数据的所有组织、部门 树
     * Date: 2020/7/22
     * Time: 17:28
     * @param $ids
     * @return array
     */
    public static function _getTreeForItemData($ids = [])
    {
        $group = $deptList = [];
        $where = [
            'select' => ['id', 'parent_id AS parentId', 'name'],
        ];
        $groupArr = Group::getList($where);
        foreach ($groupArr as $g) {
            $g['isGroup'] = 1;
            $deptArr = Department::getListByGroupId($g['id']);
            if (!empty($deptArr)) {
                foreach ($deptArr as $dpt) {
                    $dpt['checked'] = in_array($dpt['id'], $ids) ? 1 : 0;
                    $deptList[] = $dpt;
                }
                $pidArr = array_column($deptList, 'parentId');
                sort($pidArr);
                $g['children'] = TreeHelper::format($deptList, $pidArr[0]);
                $group[] = $g;
            } else {
                $g['children'] = [];
                $group[] = $g;
            }
        }
        return $group;
    }

    /**
     * 组织、部门 树
     * @param $groupId
     * @return array
     */
    public static function _getTree($groupId)
    {
        $groupArr = Group::getListWithUserCount($groupId);
        $group = [];
        foreach ($groupArr as $g) {
            $deptArr = Department::getListWithUserCount($g['id']);
            if (empty($deptArr)) {
                $g['isGroup'] = 1;
                $g['children'] = [];
                $group[] = $g;
                continue;
            }
            $pidArr = array_column($deptArr, 'parentId');
            sort($pidArr);
            $dept = TreeHelper::format($deptArr, $pidArr[0]);
            $g['isGroup'] = 1;
            $g['children'] = $dept;
            $group[] = $g;
        }
        return $group;
    }

    /**
     * 组织 列表
     * @return array
     */
    public static function _getList()
    {
        $where = [
            'select' => ['id', 'parent_id AS parentId', 'name'],
        ];
        $groupArr = Group::getList($where);
        return ((new DropListHelper())->format($groupArr));
    }
}